package com.oitsm.utils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
 * 国际化工具 - 主要用于处理在代码中出现的中文,所有代码中需要出现的中文都放到 xml文件中,然后通过I18N工具取
 * @author Arab Runner
 * Jun 25, 2011 11:55:20 AM
 */
public class I18N {
    private static Map<String, String> xmlMapping = new HashMap<String, String>();

    public static String get(String key) {
    	if(key == null){
    		return key;
    	}
        String value = xmlMapping.get(key);
        if (value == null) {
            value = key;
        }
        return value;
    }

    public static String get(String key, String[] replaces) {
        String value = xmlMapping.get(key);
        if(key == null){
    		return key;
    	}
        if (value == null) {
            value = key;
        }

        for (int i = 0; i < replaces.length; i++) {
            String replace = replaces[i];
            value = value.replace("${" + i + "}", replace==null?"":replace);
        }
        return value;
    }


    private static void parseXml() throws Exception {
        DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder dombuilder = domfac.newDocumentBuilder();
        
        String filePath = I18N.class.getClassLoader().getResource("i18n.xml").getPath();
        InputStream is = null;
        try{
        	is = new FileInputStream(filePath);
            Document doc = dombuilder.parse(is);
            Element root = doc.getDocumentElement();
            NodeList strings = root.getChildNodes();
            for (int j = 0; j < strings.getLength(); j++) {
                Node msgNode = strings.item(j);
                if (msgNode.getAttributes() == null) {
                    continue;
                }
                String key = msgNode.getAttributes().getNamedItem("key")
                        .getNodeValue();

                String value = msgNode.getAttributes()
                        .getNamedItem("value").getNodeValue();
                xmlMapping.put(key, value);
            }
        }catch(Exception e){
        	e.printStackTrace();
        }finally{
        	if(is!=null){
        		is.close();
        	}
        }
    }

    public static void init() {
        try {
        	parseXml();
        } catch (Exception e) {
        	e.printStackTrace();
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
    	I18N.init();
    }
}
